/**
 * 面包屑导航组件
 */
import React, { useMemo } from 'react'
import { useLocation, useNavigate, Link } from 'react-router-dom'
import { ChevronRight, Home } from 'lucide-react'
import { useTranslation } from '@/utils/i18n'
import { useThemeStore } from '@/stores/themeStore'

interface BreadcrumbItem {
  label: string
  path: string
}

const Breadcrumb: React.FC = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const { t } = useTranslation()
  const themePreference = useThemeStore((state) => state.theme)
  
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])

  // 路由路径到面包屑的映射
  const routeMap = useMemo(() => ({
    '/dashboard': { label: t('nav.dashboard') || '数据看板' },
    '/product-list': { label: t('product.title') || '商品列表' },
    '/product-category': { label: t('product.category') || '商品分类', parent: '商品管理', parentPath: '/product-list' },
    '/product-upload': { label: t('product.upload') || '商品上传', parent: '商品管理', parentPath: '/product-list' },
    '/order-list': { label: t('order.title') || '订单列表' },
    '/order-refund': { label: t('order.refund') || '退款管理', parent: '订单管理', parentPath: '/order-list' },
    '/user': { label: t('user.title') || '用户管理' },
    '/doc-list': { label: t('document.list') || '文档列表' },
    '/doc-collab': { label: t('document.collab') || '协同编辑', parent: '协同文档', parentPath: '/doc-list' },
    '/sales-stats': { label: t('statistics.sales') || '销售统计' },
    '/data-export': { label: t('statistics.export') || '数据导出', parent: '数据统计', parentPath: '/sales-stats' },
    '/file-manage': { label: t('file.manager') || '文件管理' },
    '/favorites': { label: t('file.favorites') || '我的收藏', parent: '文件管理', parentPath: '/file-manage' },
    '/recycle-bin': { label: t('file.recycleBin') || '回收站', parent: '文件管理', parentPath: '/file-manage' },
    '/role-manage': { label: t('role.title') || '角色管理' },
    '/permission-manage': { label: t('permission.title') || '权限管理', parent: '系统管理', parentPath: '/role-manage' },
    '/menu-manage': { label: t('menu.title') || '菜单管理', parent: '系统管理', parentPath: '/role-manage' },
    '/audit-log': { label: t('audit.title') || '审计日志', parent: '系统管理', parentPath: '/role-manage' },
    '/settings': { label: t('settings.title') || '系统设置' },
    '/chat': { label: t('chat.title') || '即时通讯中心' },
  } as Record<string, { label: string; parent?: string; parentPath?: string }>
  ), [t])

  // 生成面包屑路径
  const breadcrumbs = useMemo(() => {
    const items: BreadcrumbItem[] = []
    
    // 首页
    items.push({
      label: t('common.home') || '首页',
      path: '/dashboard'
    })

    // 如果当前路径是首页，直接返回
    if (location.pathname === '/' || location.pathname === '/dashboard') {
      return items
    }

    // 获取当前路由信息
    const currentRoute = routeMap[location.pathname]
    
    if (currentRoute) {
      // 如果有父级，添加父级
      if (currentRoute.parent && currentRoute.parentPath) {
        items.push({
          label: currentRoute.parent,
          path: currentRoute.parentPath
        })
      }
      
      // 添加当前页面
      items.push({
        label: currentRoute.label,
        path: location.pathname
      })
    } else {
      // 如果没有找到映射，尝试从路径解析
      const pathSegments = location.pathname.split('/').filter(Boolean)
      pathSegments.forEach((segment, index) => {
        const path = '/' + pathSegments.slice(0, index + 1).join('/')
        const label = formatSegment(segment)
        items.push({
          label,
          path
        })
      })
    }

    return items
  }, [location.pathname, t, routeMap])


  // 格式化路径段
  const formatSegment = (segment: string): string => {
    // 将 kebab-case 转换为中文
    const segmentMap: Record<string, string> = {
      'product-list': '商品列表',
      'product-category': '商品分类',
      'product-upload': '商品上传',
      'order-list': '订单列表',
      'order-refund': '退款管理',
      'doc-list': '文档列表',
      'doc-collab': '协同编辑',
      'sales-stats': '销售统计',
      'data-export': '数据导出',
      'file-manage': '文件管理',
      'favorites': '我的收藏',
      'recycle-bin': '回收站',
      'role-manage': '角色管理',
      'permission-manage': '权限管理',
      'menu-manage': '菜单管理',
      'audit-log': '审计日志',
      'settings': '系统设置',
      'chat': '即时通讯中心',
    }
    return segmentMap[segment] || segment
  }

  // 处理点击
  const handleClick = (path: string, isLast: boolean) => {
    if (!isLast) {
      navigate(path)
    }
  }

  if (breadcrumbs.length <= 1) {
    return null
  }

  return (
    <nav 
      className={`flex items-center space-x-2 px-4 py-3 text-sm ${
        isDark 
          ? 'bg-slate-800/50 border-b border-slate-700' 
          : 'bg-gray-50 border-b border-gray-200'
      }`}
      aria-label="面包屑导航"
    >
      {breadcrumbs.map((item, index) => {
        const isLast = index === breadcrumbs.length - 1
        
        return (
          <React.Fragment key={item.path}>
            {index === 0 ? (
              <Link
                to={item.path}
                className={`flex items-center ${
                  isDark 
                    ? 'text-slate-300 hover:text-white' 
                    : 'text-gray-600 hover:text-gray-900'
                } transition-colors`}
              >
                <Home size={16} className="mr-1" />
              </Link>
            ) : (
              <button
                onClick={() => handleClick(item.path, isLast)}
                disabled={isLast}
                className={`${
                  isLast
                    ? isDark
                      ? 'text-slate-200 font-medium cursor-default'
                      : 'text-gray-900 font-medium cursor-default'
                    : isDark
                    ? 'text-slate-300 hover:text-white'
                    : 'text-gray-600 hover:text-gray-900'
                } transition-colors`}
              >
                {item.label}
              </button>
            )}
            
            {!isLast && (
              <ChevronRight 
                size={16} 
                className={isDark ? 'text-slate-500' : 'text-gray-400'} 
              />
            )}
          </React.Fragment>
        )
      })}
    </nav>
  )
}

export default Breadcrumb

